<?php
namespace app\controller;

use think\Request;
use app\BaseController;
use app\model\SystemConfig;
use app\model\OperationLog;
use app\model\User;
use app\model\UserToken;
use think\facade\View;

class SystemController extends BaseController
{
    private $lockFile = '../init/config/init.lock';

    /**
     * 检查是否为超级管理员
     */
    private function checkAdmin(Request $request)
    {
        $user = $this->getUserFromToken($request);
        if (!$user || !$user->is_admin) {
            return false;
        }
        return $user;
    }

    /**
     * 从Token中获取用户信息
     */
    private function getUserFromToken(Request $request)
    {
        $token = $request->header('Authorization');
        if (!$token) {
            return null;
        }

        try {
            $token = str_replace('Bearer ', '', $token);
            $tokenRecord = UserToken::where('token', $token)
                ->where('is_revoked', 0)
                ->where('expired_at', '>', time())
                ->find();

            if (!$tokenRecord) {
                return null;
            }

            return User::find($tokenRecord->user_id);
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * 显示系统配置页面
     */
    public function index()
    {
        // 检查是否存在锁文件
        if (file_exists($this->lockFile)) {
            return json(['status' => 403, 'message' => '系统配置已锁定，请使用API接口进行配置']);
        }

        // 获取所有配置组
        $groups = [
            'admin' => '管理员设置',
            'basic' => '基础设置',
            'mail' => '邮件配置',
            'ai' => 'AI配置',
            'storage' => '存储配置'
        ];

        // 获取现有管理员信息
        $admin = User::where('is_admin', 1)->order('id', 'asc')->find();

        $configs = [];
        foreach ($groups as $group => $name) {
            if ($group === 'admin') {
                // 管理员配置项特殊处理
                $configs[$group] = [
                    [
                        'config_key' => 'admin_username',
                        'config_value' => $admin ? $admin->username : '',
                        'config_name' => '管理员账号',
                        'config_type' => 'text',
                        'config_description' => '超级管理员登录用户名',
                        'sort_order' => 10
                    ],
                    [
                        'config_key' => 'admin_email',
                        'config_value' => $admin ? $admin->email : '',
                        'config_name' => '管理员邮箱',
                        'config_type' => 'text',
                        'config_description' => '超级管理员邮箱地址',
                        'sort_order' => 20
                    ],
                    [
                        'config_key' => 'admin_password',
                        'config_value' => '',  // 密码不回显
                        'config_name' => '管理员密码',
                        'config_type' => 'password',
                        'config_description' => $admin ? '如需修改请输入新密码' : '超级管理员登录密码',
                        'sort_order' => 30
                    ],
                    [
                        'config_key' => 'admin_confirm_password',
                        'config_value' => '',  // 确认密码不回显
                        'config_name' => '确认密码',
                        'config_type' => 'password',
                        'config_description' => $admin ? '如需修改请再次输入新密码' : '再次输入管理员密码',
                        'sort_order' => 40
                    ]
                ];

                // 如果已存在管理员，添加提示信息
                if ($admin) {
                    array_unshift($configs[$group], [
                        'config_key' => 'admin_info',
                        'config_value' => "当前管理员：{$admin->username} ({$admin->email})",
                        'config_name' => '管理员信息',
                        'config_type' => 'info',
                        'config_description' => '已存在的管理员账号信息',
                        'sort_order' => 5
                    ]);
                }
            } else {
                $configs[$group] = SystemConfig::getGroupConfigs($group);
                foreach ($configs[$group] as &$config) {
                    if ($config['config_type'] === 'select' && !empty($config['config_options'])) {
                        $config['options'] = json_decode($config['config_options'], true);
                    }
                }
            }
        }

        View::assign([
            'groups' => $groups,
            'configs' => $configs,
            'current_group' => request()->param('group', 'admin')
        ]);

        return View::fetch('system/index');
    }

    /**
     * API: 获取系统配置
     */
    public function getConfigs(Request $request)
    {
        // 检查管理员权限
        $admin = $this->checkAdmin($request);
        if (!$admin) {
            return json(['status' => 403, 'message' => '无权访问']);
        }

        $group = $request->param('group');
        if ($group) {
            $configs = SystemConfig::getGroupConfigs($group);
        } else {
            $configs = SystemConfig::select()->toArray();
        }

        // 处理 select 类型的配置项
        foreach ($configs as &$config) {
            if ($config['config_type'] === 'select' && !empty($config['config_options'])) {
                $config['options'] = json_decode($config['config_options'], true);
            }
            // 密码类型的配置值不返回
            if ($config['config_type'] === 'password') {
                $config['config_value'] = '';
            }
        }

        return json([
            'status' => 200,
            'message' => '获取配置成功',
            'data' => $configs
        ]);
    }

    /**
     * API: 更新系统配置
     */
    public function updateConfig(Request $request)
    {
        // 检查管理员权限
        $admin = $this->checkAdmin($request);
        if (!$admin) {
            return json(['status' => 403, 'message' => '无权访问']);
        }

        try {
            $configs = $request->post();
            if (empty($configs)) {
                return json(['status' => 400, 'message' => '配置数据不能为空']);
            }

            // 更新配置
            SystemConfig::updateConfigs($configs);

            // 记录操作日志
            $this->logOperation($admin->id, 'update_config', '更新系统配置', $request);

            return json(['status' => 200, 'message' => '配置更新成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '配置更新失败：' . $e->getMessage()]);
        }
    }

    /**
     * API: 获取单个配置项
     */
    public function getConfig(Request $request)
    {
        // 检查管理员权限
        $admin = $this->checkAdmin($request);
        if (!$admin) {
            return json(['status' => 403, 'message' => '无权访问']);
        }

        $key = $request->param('key');
        if (empty($key)) {
            return json(['status' => 400, 'message' => '配置键名不能为空']);
        }

        $config = SystemConfig::where('config_key', $key)->find();
        if (!$config) {
            return json(['status' => 404, 'message' => '配置项不存在']);
        }

        // 密码类型的配置值不返回
        if ($config['config_type'] === 'password') {
            $config['config_value'] = '';
        }

        return json([
            'status' => 200,
            'message' => '获取配置成功',
            'data' => $config
        ]);
    }

    /**
     * 记录操作日志
     */
    private function logOperation($userId, $type, $desc, Request $request)
    {
        OperationLog::create([
            'user_id' => $userId,
            'operation_type' => $type,
            'operation_desc' => $desc,
            'operation_time' => time(),
            'ip_address' => $request->ip(),
            'user_agent' => $request->header('user-agent')
        ]);
    }

    /**
     * 锁定系统配置
     */
    public function lock(Request $request)
    {
        try {
            // 确保目录存在
            $lockDir = dirname($this->lockFile);
            if (!is_dir($lockDir)) {
                mkdir($lockDir, 0777, true);
            }

            // 检查是否已设置管理员账号
            $admin = User::where('is_admin', 1)->find();
            if (!$admin) {
                return json(['status' => 400, 'message' => '请先设置超级管理员账号后再锁定配置']);
            }

            // 创建锁文件
            file_put_contents(
                $this->lockFile,
                json_encode([
                    'locked_at' => date('Y-m-d H:i:s'),
                    'admin_username' => $admin->username
                ])
            );

            return json(['status' => 200, 'message' => '系统配置已锁定，请使用超级管理员账号登录']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '锁定失败：' . $e->getMessage()]);
        }
    }

    /**
     * 保存系统配置
     */
    public function save(Request $request)
    {
        try {
            $data = $request->post();
            
            // 处理管理员账号配置
            if (isset($data['admin_username'])) {
                // 验证管理员账号信息
                if (empty($data['admin_username']) || empty($data['admin_email'])) {
                    return json(['status' => 400, 'message' => '管理员用户名和邮箱不能为空']);
                }

                if (!filter_var($data['admin_email'], FILTER_VALIDATE_EMAIL)) {
                    return json(['status' => 400, 'message' => '邮箱格式不正确']);
                }

                // 查找现有管理员
                $admin = User::where('is_admin', 1)->order('id', 'asc')->find();
                
                if ($admin) {
                    // 更新管理员信息
                    $updateData = [
                        'username' => $data['admin_username'],
                        'email' => $data['admin_email']
                    ];

                    // 如果提供了新密码，则更新密码
                    if (!empty($data['admin_password'])) {
                        if ($data['admin_password'] !== $data['admin_confirm_password']) {
                            return json(['status' => 400, 'message' => '两次输入的密码不一致']);
                        }
                        $updateData['password'] = password_hash($data['admin_password'], PASSWORD_DEFAULT);
                    }

                    // 检查用户名和邮箱是否与其他用户冲突
                    $existUser = User::where('id', '<>', $admin->id)
                        ->where(function($query) use ($data) {
                            $query->where('username', $data['admin_username'])
                                  ->whereOr('email', $data['admin_email']);
                        })
                        ->find();
                    
                    if ($existUser) {
                        return json(['status' => 400, 'message' => '用户名或邮箱已被其他用户使用']);
                    }

                    // 更新管理员信息
                    User::where('id', $admin->id)->update($updateData);
                } else {
                    // 创建新管理员账号
                    if (empty($data['admin_password']) || empty($data['admin_confirm_password'])) {
                        return json(['status' => 400, 'message' => '创建管理员时密码不能为空']);
                    }

                    if ($data['admin_password'] !== $data['admin_confirm_password']) {
                        return json(['status' => 400, 'message' => '两次输入的密码不一致']);
                    }

                    // 检查用户名和邮箱是否已存在
                    $existUser = User::where('username', $data['admin_username'])
                        ->whereOr('email', $data['admin_email'])
                        ->find();
                    
                    if ($existUser) {
                        return json(['status' => 400, 'message' => '用户名或邮箱已存在']);
                    }

                    // 创建管理员账号
                    User::create([
                        'username' => $data['admin_username'],
                        'email' => $data['admin_email'],
                        'password' => password_hash($data['admin_password'], PASSWORD_DEFAULT),
                        'is_verified' => 1,
                        'is_admin' => 1
                    ]);
                }

                // 移除管理员配置项，不保存到配置表
                unset($data['admin_username'], $data['admin_email'], 
                      $data['admin_password'], $data['admin_confirm_password']);
            }

            // 更新其他配置项
            if (!empty($data)) {
                SystemConfig::updateConfigs($data);
            }

            return json(['status' => 200, 'message' => '配置保存成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '配置保存失败：' . $e->getMessage()]);
        }
    }
} 